<template>
	<div style="padding-bottom: 40px;">

		<van-sticky>
			<div class="topdropdown">
				<van-dropdown-menu>
					<van-dropdown-item v-model="params.storeId" :options="option1" title="店铺" @change="storeChange" />
					<van-dropdown-item v-model="searchObj.value2" :options="option2" title="类型" @change="typeChange" />
				</van-dropdown-menu>
				<div class="dropdownLeft" v-if="params.storeId"></div>
				<div class="dropdownRight" v-if="searchObj.value2"></div>
			</div>
			<div class="searchBox">
				<van-search v-model="params.deviceName" :placeholder="placeholder" @search="handleSearch">
					<template #right-icon>
						<div class="search-confirm" @click.stop="handleSearch">
							<span style="margin-right: 10px;height: 24px;">|</span>
							<span class="search-text">搜索</span>
						</div>
					</template>
				</van-search>
				<div class="condition">
					<van-field v-model="params.startTime" readonly name="datePicker" placeholder="请选择开始时间"
						@click="timekai('startTime')" style="width:40% ;cursor: pointer;" input-align="center" />
					<van-field v-model="params.endTime" readonly name="datePicker" placeholder="请选择结束时间"
						@click="timekai('endTime')" style="width:40% ;cursor: pointer;" input-align="center" />
				</div>
			</div>
		</van-sticky>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" finished-text="没有更多数据了"
				:finished="finished" @load="getdata">
				<DeviceList :list="list" :mark="mark"></DeviceList>
			</van-list>
		</van-pull-refresh>
		<!-- 时间选择 -->
		<van-popup v-model:show="showPicker" destroy-on-close position="bottom" safe-area-inset-bottom round>
			<van-date-picker v-model="currentDate" @confirm="onConfirm" @cancel="showPicker = false" />
		</van-popup>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
	} from "vue";

	import {
		getUserid
	} from '@/utils/auth';
	import {
		deviceTransferRecordList
	} from '@/api/deviceEntity';
	import {
		StoresList
	} from '@/api/deviceRechargeConfig';

	const getTodayString = () => {
	  const now = new Date();
	  const year = now.getFullYear();
	  const month = (now.getMonth() + 1).toString().padStart(2, '0');
	  const day = now.getDate().toString().padStart(2, '0');
	  return `${year}-${month}-${day}`;
	};

	const params = ref({
		size: 10,
		pages: 1,
		userId: getUserid(),
		type: [],
		startTime: getTodayString(),
		endTime: getTodayString(),
		storeId: '',
		deviceName:''
	});

	const list = reactive([]);
	const mark = ref('transferRecord');
	const loading = ref(false);
	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);

	const placeholder = ref('请输入设备名称搜索');
	var option1 = reactive([]);

	const option2 = [{
		text: '全部',
		value: 0
	}, {
		text: '转移',
		value: 1
	}, {
		text: '解绑',
		value: 2
	}];

	const searchObj = ref({
		value1: '',
		value2: 0,
		searchValue: undefined
	});

	onMounted(() => {
		getdata();
		getstore();
	});
	// 商店下拉列表
	const getstore = async () => {
		const userId = {
			userId: getUserid(),
		}
		try {
			const response = await StoresList(userId);
			const records = response.data || [];
			option1 = [{
				text: "全部",
				value: ''
			}, ...records.map((item) => ({ // 展开原数组
				text: item.storeName,
				value: item.id,
			}))];
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	}

	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceTransferRecordList(params.value);
			const records = response.data.records || [];
			// 新增：格式化时间
			const formattedRecords = records.map(item => ({
				...item,
				// 添加格式化后的时间字段（保留原始 createTime）
				createTime: formatISODate(item.createTime),
			}));
			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...formattedRecords);
			} else {
				list.push(...formattedRecords);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error('获取数据失败', err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	const timemark = ref('');
	const showPicker = ref(false);
	const currentDate = ref([
		new Date().getFullYear().toString(),
		(new Date().getMonth() + 1).toString().padStart(2, '0'),
		new Date().getDate().toString().padStart(2, '0')
	]);
	const timekai = (type) => {
		timemark.value = type;
		showPicker.value = true;
	};
	const onConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		currentDate.value = selectedValues;
		showPicker.value = false;
		// 身份证有效期
		if (timemark.value === 'startTime') {
			params.value.startTime = selectedValues.join('-');
		} else {
			params.value.endTime = selectedValues.join('-');
		}
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;

		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;
		getdata(true); // 传入 true 表示是刷新操作
	}
	// 筛选
	const storeChange = (id) => {
		params.value.storeId = id
		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;
		getdata(true); // 传入 true 表示是刷新操作
	};
	const typeChange = (value) => {
		if (value == 0) {
			params.value.type = ''
			searchObj.value.value2 = 0;
		} else {
			params.value.type = Number(value) - 1
			searchObj.value.value2 = value;
		}

		// 立即清空列表
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value.pages = 1;
		params.value.type = '';
		searchObj.value.value2 = 0;

		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 输入框搜索
	const handleSearch = (item) => {
		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1;
		params.value.type = '';
		params.value.storeId = '';

		searchObj.value.value2 = 0;
		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};
	// 时间格式化工具函数
	const formatISODate = (isoString) => {
		// 修复格式问题：将 "+0000" 转成 "+00:00"
		if (!isoString) return "-"; // 处理空值
		try {
			const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
			const date = new Date(fixedDateString);
			// 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
			return date.toLocaleString("zh-CN", {
				year: "numeric",
				month: "2-digit",
				day: "2-digit",
				hour: "2-digit",
				minute: "2-digit",
				// second: "2-digit",
				hour12: false // 强制 24 小时制
			}).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
		} catch {
			return "-"; // 解析失败时返回占位符
		}
	};
</script>

<style lang="scss" scoped>
	:deep(.van-dropdown-menu__bar) {
		box-shadow: none;

		.van-dropdown-menu__title {
			color: orange;
		}

		.van-dropdown-menu__title:after {
			border-color: transparent transparent orange orange;
		}
	}

	:deep(.searchBox) {
		background-color: white;

		.van-search {
			background-color: white;

			// 搜索框
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				// border-radius: 5px;
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2FBC3C;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		// 文字
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}

	.topdropdown {
		position: relative;

		.dropdownLeft {
			position: absolute;
			bottom: 0;
			left: 16%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}

		.dropdownRight {
			position: absolute;
			bottom: 0;
			right: 14%;
			width: 20%;
			height: 3px;
			background-color: orange;
		}
	}

	.condition {
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-around;
		gap: 10px;
		padding: 0 10px;
		box-sizing: border-box;

		.conditionLi {
			padding: 6px;
			border-radius: 8px;
			border: 1px solid #ddd;
			font-size: 12px;
			background-color: #FFF;
		}
	}

	:deep(.van-field__control:read-only){
    	cursor: pointer;
	}
</style>
